package dbinit.csv;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.StringTokenizer;

import core.category.model.Category;
import core.product.model.Product;
import core.profile.model.BasicProfile;

import dbinit.InitBasicProfile;
import dbinit.InitCategory;
import dbinit.InitPrice;
import dbinit.InitPriceType;
import dbinit.InitProduct;
import dbinit.InitProductAddress;
import dbinit.InitProductOwner;
import dbinit.InitProductType;

import dbinit.csv.csvreader.CsvReader;

public class ImportProductCsv 
{	
	public static void doImport(String Filename)
	{

		try {
			CsvReader productdata = new CsvReader(Filename);
			
			productdata.readHeaders();
			while (productdata.readRecord())
			{
				String sku=productdata.get("sku");
				String name =productdata.get("name");
				String imagePath=productdata.get("imagePath");
				String thumbnail=productdata.get("thumbnail");
				String avalable1=productdata.get("avalable");
				String enabled1=productdata.get("enabled");
				String price1=productdata.get("price");
				String specialprice1=productdata.get("specialprice");
				String startdate1=productdata.get("startdate");
				String enddate1=productdata.get("enddate");
				String comment=productdata.get("comment");
				String producttype =productdata.get("producttype");
				String ownerEmail = productdata.get("ownerEmail");
				String city = productdata.get("city");
				String region = productdata.get("region");
				String state = productdata.get("state");
				String country = productdata.get("country");
				String continents = productdata.get("continents");
				String zip = productdata.get("zip");
				String address = productdata.get("address");
				String bedrooms = productdata.get("Bedrooms");
				String bathrooms = productdata.get("Bathrooms");
				String website = productdata.get("website");
				  

                // create category path here
				String category = "/world" ;
				if(continents !=null && continents.trim()!= "" )
				{
					category = category + "/" + continents ;
					ImportCategory.doImport(continents, category, "continent");
				}
				if(country !=null && country.trim()!= "" )
				{
					category = category + "/" + country ;
					ImportCategory.doImport(country, category, "country");
				}
				if(state !=null && state.trim()!= "" )
				{
					category = category + "/" + state ;
					ImportCategory.doImport(state, category, "state");
				}
				if(region !=null && region.trim()!= "" )
				{
					category = category + "/" + region ;
					ImportCategory.doImport(region, category, "region");
				}
				if(city !=null && city.trim()!= "" )
				{
					category = category + "/" + city ;
					ImportCategory.doImport(city, category, "city");
				}

				float price=Float.parseFloat(price1);
				
				float specialprice= 0f ;
				if(specialprice1 != null && specialprice1.trim()!= "")
				{
					specialprice=Float.parseFloat(specialprice1);
				}
				
				boolean avalable = Boolean.parseBoolean(avalable1); 
				boolean enabled = Boolean.parseBoolean(enabled1); 
				
				SimpleDateFormat formatter=new SimpleDateFormat("dd/MM/yy");
				Date startdate2 = null ;
				java.sql.Date startdate = null ;
				if(startdate1 != null && startdate1.trim()!="")
				{
					startdate2 = (Date)formatter.parse(startdate1);
					startdate = new java.sql.Date(startdate2.getTime());
				}
				Date enddate2 = null ;
				java.sql.Date enddate = null;
				if(enddate1 != null && enddate1.trim()!= "")
				{
					enddate2 = (Date)formatter.parse(enddate1); 
					enddate = new java.sql.Date(enddate2.getTime());
				}
				Long productTypeId = InitProductType.createOrGetUuidByName(producttype);
				Long  ptid = InitPriceType.doinit("Sale Price");
				
				Long productId = InitProduct.doinit(sku,name,imagePath,thumbnail, productTypeId, null,avalable, enabled) ;
				Long priceId = InitPrice.doinit(price,specialprice, startdate, enddate,ptid,comment,productId);
				Set<Long> prices = new HashSet<Long>();
				prices.add(priceId);
				InitProduct.updateProductPrice(InitProduct.getProductByUuid(productId), prices.iterator());
				
				Product p = InitProduct.getProductByUuid(productId);
				// set product owner
				//get product owner
				BasicProfile prodOwner = InitBasicProfile.getBasicProfileByEmail(ownerEmail);
				if(prodOwner != null)
				{
					InitProductOwner.doinit(productId,prodOwner.getUuid());
				}
				// set product address
				InitProductAddress.doinit(sku, address, "", "000" , zip);
				// Import product attributes.....
				//InitAttribute.getAttributeByName(bedrooms);
				//InitProductAv.getProductAv(product, attributeSet, attribute)
				StringTokenizer categories = new StringTokenizer(category , "/");
				while(categories.hasMoreTokens())
				{
					String cateName = categories.nextToken();
					Iterator<Category> catelst = InitCategory.getCategoriesByName(cateName).iterator();
					while(catelst.hasNext())
					{
						Category cat = catelst.next();
						String path = cat.getPath();
						System.out.println(path+" ---------------------");
						StringTokenizer cateTree = new StringTokenizer(path , "/");
						while(cateTree.hasMoreTokens())
						{
							String newcate = cateTree.nextToken();
							String newPath = path.substring(0,path.indexOf(newcate)) + newcate ;
							System.out.println(newcate + "  "  + newPath);
							Category newCategory = InitCategory.getCategoryByNameAndPath(newcate, newPath);
							InitCategory.setProduct(newCategory , p);
						}
					}
				}
			}
			
			productdata.close();
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) 
	{
		
			doImport("source/product_info.csv");
		
	}

}
